<!-- 项目设备页面 -->
<template>
  <div class="project-container">
    <div class="project-infor-cards">
      <InfoCard :project="selectedProject" />
      <Rule :proj_oid="projectStore.projectInfo.proj_oid" />
      <cardEq :proj_oid="projectStore.projectInfo.proj_oid" />
      <Schedule
        :tableDataFormatter="tableDataFormatter"
        :proj_oid="projectStore.projectInfo.proj_oid"
      />
      <Note :proj_oid="projectStore.projectInfo.proj_oid" />
    </div>

    <div
      v-if="false"
      class="my_model"
      style="position: fixed; width: 300px; height: 300px; top: 0; z-index: -11"
    >
      <ModelView></ModelView>
    </div>
    <el-card v-loading='table_Loadings' shadow="hover">
      <div style="position: relative" class="equip-list">
        <div class="equip-buttons">
          <span class="equip-title_span"
            >设备一览表<span
              style="font-size: 16px; color: red"
              class="equip_text_num"
              >（共{{ tableNum }}台设备）</span
            ></span
          >

          <div
            style="
              display: flex;
              justify-content: flex-end;
              align-items: center;
            "
          >
            <el-button-group>
              <el-popover placement="bottom-start" :width="550">
                <template #reference>
                  <el-button
                    size="small"
                    type="primary"
                  
                    class="dr23"
                    >批量生成文件</el-button
                  >
                </template>
                <div
                  style="
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    padding: 10px;
                  "
                >
                  <el-button
                    @click="SC(1)"
                    size="small"
                    
                    type="primary"
                    class="dr23"
                    >生成设计条件和校审记录封面</el-button
                  >

                  <el-button
                    @click="SC(2)"
                    size="small"
                   
                    type="success"
                    class="dr23"
                    >生成计算书封面</el-button
                  >

                  <el-button
                    @click="SC(3)"
                    size="small"
                  
                    type="danger"
                    class="dr23"
                    >生成固定式压力容器风险评估报告</el-button
                  >
                </div>
              </el-popover>
              <el-button type="primary" size="small" 
                >工艺条件输入</el-button
              >
              <el-popover placement="bottom-start" :width="200">
                <template #reference>
                  <el-button type="primary" size="small"
                    >设备模型计算结果输出</el-button
                  >
                </template>
                <div style="font-size: 13px">选择单位：</div>
                <el-radio-group v-model="sizeSend" class="ml-4">
                  <el-radio label="mm" size="small">mm</el-radio>
                  <el-radio label="In" size="large">In</el-radio>
                </el-radio-group>
                <div style="display: flex; flex-direction: row-reverse">
                  <el-button
                    size="small"
                    @click="mulitExportEquipCalData"
                    type="success"
                    >输出</el-button
                  >
                  &nbsp;&nbsp;
                  <el-button
                    size="small"
                    @click="mulitPushEquipCalData"
                     type="primary"
                    >推送数据</el-button
                  >
                </div>
              </el-popover>

              <el-button
                type="primary"
                size="small"
                @click="mulitExportEquipData"
                >批量输出输入数据</el-button
              >

              <el-upload
                class="upload-demo"
                action="#"
                :show-file-list="false"
                :http-request="checkNozzle"
              >
                <el-button type="primary" size="small">管口信息会签</el-button>
              </el-upload>
              <el-button
                type="primary"
                size="small"
                @click="ExportSupportDatasFn"
                >输出结构基础会签表</el-button
              >
              <el-button type="primary" size="small" 
                >仪表条件会签</el-button
              >
            </el-button-group>

            <el-button-group v-if="false">
              <el-button type="warning" size="small" >复用</el-button>
            </el-button-group>

            <el-button-group v-if="false" class="create-del-equip">
              <el-tooltip content="新建设备" placement="top" effect="dark">
                <el-button
                  type="primary"
                  color="#626aef"
                  size="small"
                  :icon="Plus"
                  tag="新建设备"
                  @click="newDioFn"
                />
              </el-tooltip>
              <el-tooltip content="删除设备" placement="top" effect="dark">
                <el-button
                  type="danger"
                  size="small"
                  :icon="Delete"
                  @click="deleteEquipment"
                />
              </el-tooltip>
            </el-button-group>
          </div>
        </div>
        <!-- <EquipList /> -->
        <EquipList
        :table_Loading='table_Loading'
        :Myproj_oid='projectStore.projectInfo.proj_oid'
        :tableHeaderStr='tableHeader'
        :custom_att1_val_option='custom_att1_val_option'
        :installation_mode_class='installation_mode_class'
        :equip_designer_class='equip_designer_class'
          @tableDataSend="tableDataSend"
          :equipEquip_class="equipEquip_class"
          :equipOptions="equipOptions"
          :nameOptions="nameOptions"
          :equipEquip_no="equipEquip_no"
          @tableList="tableList"
          @SelectMajorFn="SelectMajorFn"
          :equipments="equipments"
          :equip_checker_class='equip_checker_class'
:approver_class='approver_class'
          :auditor_class='auditor_class'
        />
      </div>
    </el-card>

    <el-dialog
      @close="closeFrom(destEquipInfoRef)"
      title="新建设备"
      v-model="newDio"
      width="25%"
    >
      <el-form
        ref="destEquipInfoRef"
        size="small"
        :model="destEquipInfo"
        :rules="destEquipInfoRules"
        label-width="100px"
      >
        <el-form-item label="主项号" prop="unit_oid">
          <el-select
            size="small"
            style="width: 100%"
            v-model="destEquipInfo.unit_oid"
            placeholder="请选择主项号"
          >
            <el-option
              v-for="(item, index) in unit_oidOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备名称" prop="equip_name">
          <el-input
            size="small"
            v-model="destEquipInfo.equip_name"
            placeholder="请输入设备名称"
          />
        </el-form-item>
        <el-form-item label="设备位号" prop="equip_no">
          <el-input
            size="small"
            v-model="destEquipInfo.equip_no"
            placeholder="请输入设备位号"
          />
        </el-form-item>
        <el-form-item label="设备种类" prop="equip_class">
          <el-select-v2
            style="width: 100%"
            filterable
            :options="[
              { value: '容器', label: '容器' },
              { value: '塔器', label: '塔器' },
              { value: '反应器', label: '反应器' },
              { value: '大型储罐', label: '大型储罐' },
              { value: '球罐', label: '球罐' },
              { value: '换热器', label: '换热器' },
            ]"
            size="small"
            placeholder="请输入设备种类"
            v-model="destEquipInfo.equip_class"
          >
          </el-select-v2>
        </el-form-item>
        <el-form-item label="安装方式" prop="installation_mode">
          <el-select-v2
            style="width: 100%"
            filterable
            :options="[
              { value: '裙座', label: '裙座' },
              { value: '耳座', label: '耳座' },
              { value: '刚性环', label: '刚性环' },
              { value: '支腿', label: '支腿' },
              { value: '支承式', label: '支承式' },
              { value: '鞍座', label: '鞍座' },
            ]"
            size="small"
            placeholder="请输入安装方式"
            v-model="destEquipInfo.installation_mode"
          >
          </el-select-v2>
        </el-form-item>
        <el-form-item label="设备图号" prop="equip_dwg_no">
          <el-input
            size="small"
            v-model="destEquipInfo.equip_dwg_no"
            placeholder="请输入设备图号"
          />
        </el-form-item>
        <el-form-item label="设备类别" prop="vessel_type">
          <!-- <el-input
            size="small"
            v-model="destEquipInfo.vessel_type"
            placeholder="请输入容器类型"
          /> -->

          <el-select
            style="width: 100%"
            size="small"
            placeholder="请输入设备类别"
            v-model="destEquipInfo.vessel_type"
            filterable
          >
            <el-option
              v-for="(item, index) in [
               {
                    value: 'Ⅰ',
                    label: 'Ⅰ',
                  },
                  {
                    value: 'Ⅱ',
                    label: 'Ⅱ',
                  },
                  {
                    value: 'Ⅲ',
                    label: 'Ⅲ',
                  },
 
                  {
                    value: 'I/SAD',
                    label: 'I/SAD',
                  },
                  {
                    value: 'II/SAD',
                    label: 'II/SAD',
                  },
                  {
                    value: 'III/SAD',
                    label: 'III/SAD',
                  },


                   {
                    value: '类外',
                    label: '类外',
                  },
              ]"
              :key="index"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="台数" prop="equip_count">
          <el-input
            type="number"
            size="small"
            v-model="destEquipInfo.equip_count"
            placeholder="请输入台数"
          />
        </el-form-item>
        <el-form-item label="空设备重量" prop="equip_dry_weight">
          <el-input
            type="number"
            size="small"
            v-model="destEquipInfo.equip_dry_weight"
            placeholder="请输入重量"
          />
        </el-form-item>
        <el-form-item label="特材重量" prop="special_material_weight">
          <el-input
            type="number"
            size="small"
            v-model="destEquipInfo.special_material_weight"
            placeholder="请输入重量"
          />
        </el-form-item>
        <el-form-item label="设计人" prop="equip_designer">
          <el-select-v2
            style="width: 100%"
            filterable
            :options="[{ value: '王汤', label: '王汤' }]"
            size="small"
            placeholder="请输入设计人"
            v-model="destEquipInfo.equip_designer"
          >
          </el-select-v2>
        </el-form-item>
        <el-form-item label="校核人" prop="equip_checker">
          <el-select-v2
            style="width: 100%"
            filterable
            :options="[{ value: '王汤', label: '王汤' }]"
            size="small"
            placeholder="请输入校核人"
            v-model="destEquipInfo.equip_checker"
          >
          </el-select-v2>
        </el-form-item>
        <el-form-item label="审批人" prop="auditor">
          <el-select-v2
            style="width: 100%"
            filterable
            :options="[{ value: '王汤', label: '王汤' }]"
            size="small"
            placeholder="请输入审批人"
            v-model="destEquipInfo.auditor"
          >
          </el-select-v2>
        </el-form-item>
        <el-form-item label="审定人" prop="approver">
          <el-select-v2
            style="width: 100%"
            filterable
            :options="[{ value: '王汤', label: '王汤' }]"
            size="small"
            placeholder="请输入审定人"
            v-model="destEquipInfo.approver"
          >
          </el-select-v2>
        </el-form-item>

        <!-- <el-form-item label="条件发送时间" prop="condition_iss_time">
			<el-date-picker
			style="width: 100%;"
        v-model="destEquipInfo.condition_iss_time"
        type="datetime"
        placeholder="选择条件发送时间"
		value-format="yyyy-MM-dd HH:mm:ss"
        format="yyyy-MM-dd HH:mm:ss"
        >
		</el-date-picker>"
     
         
        </el-form-item> -->
        <el-form-item>
          <div style="width: 100%; display: flex; flex-direction: row-reverse">
            <el-button @click="newDio = false">取 消</el-button>
            &nbsp;&nbsp;&nbsp;&nbsp;
            <el-button type="primary" @click="handleCopyEquip(destEquipInfoRef)"
              >确 定</el-button
            >
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup name="Project">
import { defineAsyncComponent, ref, reactive, onMounted, watch } from "vue";
import { Plus, Delete, Warning } from "@element-plus/icons-vue";
import { useProjectStore } from "/@/stores/project";
// import { ElMessageBox } from 'element-plus'
import { useEquipmentStore } from "../../stores/equipment";
/* 引入组件 */
const InfoCard = defineAsyncComponent(() =>
  import("./components/infoCard.vue")
);
const Rule = defineAsyncComponent(() => import("./components/rule.vue"));
const cardEq = defineAsyncComponent(() =>
  import("./components/cardEquipList.vue")
);
const Schedule = defineAsyncComponent(() =>
  import("./components/schedule.vue")
);
const Note = defineAsyncComponent(() => import("./components/note.vue"));
const EquipList = defineAsyncComponent(() =>
  import("./components/equipList.vue")
);

/* 引入API */
import {
  DeleteEquip,
  GetCheckNozzleTable,
  getEquipments,
  ExportZipForModelInput,
  ExportZipForModel,
  PushModelCalDatasToDataCenter,
  CreateCheckNozzleTable,
  addEquipV2,
  CreateVesselRiskReport,
  CreateCalculationBook,
  CreateDesignConditionAndCheckedRecord,
  ExportSupportDatas,
  GetEquipCustomAttributes,
} from "/@/api/equipment";
import { GetUnits } from "/@/api/projectManage/projectList";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
const ModelView = defineAsyncComponent(() => import("../equip/index.vue"));
/* 定义变量内容 */
let selectedProject = ref({});
const projectStore = useProjectStore();
let EquipmentStore = useEquipmentStore();
let equipments = ref([]);
let tempEquipList = ref([]);

let table_Loading = ref(true)
let tableNum = ref(0);

let tableDataFormatter = ref([]);
let tableDataSend = (data) => {
  tableDataFormatter.value = data;
  tableNum.value = data.length;
};

let destEquipInfo = ref({
  unit_oid: "",
  equip_name: "",
  equip_no: "",
  equip_class: null,
  installation_mode: null,
  equip_dwg_no: "",
  vessel_type: "",
  equip_count: "",
  equip_dry_weight: "",
  special_material_weight: "",
  equip_designer: null,
  equip_checker: null,
  auditor: null,
  approver: null,
});
let destEquipInfoRules = ref({
  unit_oid: [{ required: true, message: "请输入主项号", trigger: "blur" }],
  equip_name: [{ required: true, message: "请输入设备名称", trigger: "blur" }],
  equip_no: [{ required: true, message: "请输入设备编号", trigger: "blur" }],
  equip_class: [{ required: true, message: "请输入设备种类", trigger: "blur" }],
  installation_mode: [
    { required: true, message: "请输入安装方式", trigger: "blur" },
  ],

  equip_dwg_no: [
    { required: true, message: "请输入设计图号", trigger: "blur" },
  ],
  vessel_type: [{ required: true, message: "请输入设备类型", trigger: "blur" }],
  equip_count: [{ required: true, message: "请输入台数", trigger: "blur" }],
  equip_dry_weight: [
    { required: true, message: "请输入空设备重量", trigger: "blur" },
  ],
  special_material_weight: [
    { required: true, message: "请输入特材重量", trigger: "blur" },
  ],
  equip_designer: [
    { required: true, message: "请输入设计人", trigger: "blur" },
  ],
  equip_checker: [{ required: true, message: "请输入校核人", trigger: "blur" }],
  auditor: [{ required: true, message: "请输入审批人", trigger: "blur" }],
  approver: [{ required: true, message: "请输入审定人", trigger: "blur" }],
});

let sizeSend = ref("mm");

let ExportSupportDatasFn = async () => {
  if (sectionTableData.value.length == 0) {
    ElMessage({
      message: "请选择要导出的设备",
      type: "warning",
    });
    return;
  }
  let res = await ExportSupportDatas({
    proj_oid: selectedProject.value.proj_oid,
    equip_oids: sectionTableData.value.map((v) => v.equip_oid),
    user: JSON.parse(localStorage.getItem("userMessage")).user_name,
  });
  if (res.data) {
    try {
      let filename = res.headers; //下载后文件名
      let filename2 = ""; //下载后文件名
      filename = filename["content-disposition"];
      filename = window.decodeURI(filename);
      filename2 = filename.split(";")[1].split("filename*=UTF-8''")[1];
      filename = filename.split(";")[1].split("filename=")[1];
      const link = document.createElement("a"); // 创建a标签
      const blo = new Blob([res.data], { type: res.data.type }); // 设置下载格式
      link.style.display = "none";
      const url = window.URL.createObjectURL(blo);
      console.log(url);
      link.href = url;
      if (filename == undefined) {
        filename = filename2;
      }
      link.download = filename;

      // link.setAttribute('download', "fileName")3
      document.body.appendChild(link);
      link.click(); // 触发下载
      window.URL.revokeObjectURL(url); // 释放掉blob对象
      document.body.removeChild(link);
      ElMessage({
        message: "成功生成文件",
        type: "success",
      });
    } catch (error) {
      const blo = new Blob([res.data], { type: res.data.type }); // 设置下载格式
      let resData = await blo.text();

      ElMessage({
        message: resData,
        type: "error",
      });
    }
  }
};

let select_model_stage_class = ref([])
let select_equip_check_class = ref([])
let select_installation_mode_class = ref([])
let select_equip_checker_class = ref([])
let SelectMajorFn = ({ text, title }) => {
  if (title == "SelectMajor") {
    SelectMajor.value = text;
  } else if (title == "equip_nameInput") {
    equip_nameInput.value = text;
  } else if (title == "equipEquip_no") {
    SelectEquip_no.value = text;
  } else if (title == "equipEquip_class") {
    SelectEquip_class.value = text;
  } else if (title == "drawing_stage") {
    drawing_stage.value = text;
  }else if(title=='installation_mode_class'){
      select_installation_mode_class.value = text

    }
    else if(title=='equip_designer_class'){
      select_equip_designer_class.value = text

    }
    else if(title=='equip_checker_class'){
      select_equip_checker_class.value = text

    }
    else if(title=='auditor_class'){
      select_auditor_class.value = text

    }
    else if(title=='approver_class'){
      select_approver_class.value = text

    }
    else if(title=='equip_check_class'){
     
     select_equip_check_class.value = text

   }else if(title=='model_stage_class'){
    select_model_stage_class.value = text
   }else if (title=='custom_att1_val_class'){
      custom_att1_val_class.value = text
    }
};

let select_equip_designer_class = ref('')

let closeFrom = () => {
  destEquipInfoRef.value.resetFields();
};

let destEquipInfoRef = ref("");

let newDio = ref(false);

let checkNozzle = async (file) => {
  console.log(file);
  let fromData = new FormData();
  fromData.append("file", file.file);

  let respone = await CreateCheckNozzleTable(fromData);

  if (!respone.data.endsWith(".xlsx")) {
    ElMessage({
      message: "文件上传类型错误，请重新上传",
      type: "error",
      duration: 1000,
    });
    return;
  }
  ElNotification({
    position: "top-right",
    title: "正在对比",
    message: `正在对比生成报告，请稍后....`,
    type: "warning",
    duration: 3000,
  });
  let res = await GetCheckNozzleTable({
    proj_oid: selectedProject.value.proj_oid,
    path: respone.data,
  });

  //在headers中截取filename
  let filename = res.headers; //下载后文件名
  let filename2 = ""; //下载后文件名
  filename = filename["content-disposition"];
  filename = window.decodeURI(filename);
  filename2 = filename.split(";")[1].split("filename*=UTF-8''")[1];
  filename = filename.split(";")[1].split("filename=")[1];
  let blob = new Blob([res.data]);
  let downloadElement = document.createElement("a");
  let href = window.URL.createObjectURL(blob); //创建下载的链接
  downloadElement.href = href;
  if (filename == undefined) {
    filename = filename2;
  }
  downloadElement.download = filename;
  //此处也可以将filename写死 "filename.xlsx"
  document.body.appendChild(downloadElement);
  downloadElement.click(); //点击下载

  document.body.removeChild(downloadElement); //下载完成移除元素
  window.URL.revokeObjectURL(href); //释放掉blob对象
};



let installation_mode_class = ref([])

let sectionTableData = ref([]);
let tableList = (data) => {
  sectionTableData.value = data;
};

let select_approver_class = ref([])
let select_auditor_class = ref([])
watch(
  () => EquipmentStore.UpgradeEquipCount,
  () => {
    getEquipmentList(
      projectStore.projectInfo.proj_oid,
      SelectMajor.value,
      SelectEquip_no.value,
      SelectEquip_class.value,
      equip_nameInput.value,
      drawing_stage.value,
      select_installation_mode_class.value,
      select_equip_checker_class.value,
      select_equip_designer_class.value,
      select_auditor_class.value,
      select_approver_class.value,
      select_equip_check_class.value,
      select_model_stage_class.value,
      custom_att1_val_class.value,
    );
  }
);

let SC = async (num) => {
  let res;
  if (sectionTableData.value.length == 0) {
    ElMessage({
      message: "请选择设备",
      type: "warning",
    });
    return;
  }
  if (num == 1) {
    res = await CreateDesignConditionAndCheckedRecord({
      equipOids: sectionTableData.value.map((v) => v.equip_oid),
    });
  }

  if (num == 2) {
    res = await CreateCalculationBook({
      equipOids: sectionTableData.value.map((v) => v.equip_oid),
    });
  }
  if (num == 3) {
    res = await CreateVesselRiskReport({
      equipOids: sectionTableData.value.map((v) => v.equip_oid),
    });
  }

  let filename = res.headers; //下载后文件名
  let filename2 = ""; //下载后文件名
  filename = filename["content-disposition"];
  filename = window.decodeURI(filename);
  filename2 = filename.split(";")[1].split("filename*=UTF-8''")[1];
  filename = filename.split(";")[1].split("filename=")[1];
  const link = document.createElement("a"); // 创建a标签
  const blo = new Blob([res.data], { type: res.data.type }); // 设置下载格式
  link.style.display = "none";
  const url = window.URL.createObjectURL(blo);
  console.log(url);
  link.href = url;
  if (filename == undefined) {
    filename = filename2;
  }
  link.download = filename;

  // link.setAttribute('download', "fileName")3
  document.body.appendChild(link);
  link.click(); // 触发下载
  window.URL.revokeObjectURL(url); // 释放掉blob对象
  document.body.removeChild(link);
  ElMessage({
    message: "成功生成文件",
    type: "success",
  });
};

let table_Loadings = ref(true)

let handleCopyEquip = (formEl) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      // 保存数据
     let res = await addEquipV2({
        ...destEquipInfo.value,
        proj_oid: selectedProject.value.proj_oid,
      });

      if(res === 'True'){
        ElMessage({
        message: "新增成功",
        type: "success",
      });
      }else{
        ElMessage({
        message: "新增失败",
        type: "success",
      });
      }
     
      EquipmentStore.UpgradeEquipCount += 1;
    }
  });
};


let mulitPushEquipCalData = async () => {
  if (sectionTableData.value.length == 0) {
    ElMessage({
      message: "请选择要输出的设备",
      type: "warning",
    });
    return;
  }
  let data = {
    proj_no:projectStore.projectInfo.proj_no,
    equip_oids:sectionTableData.value.map(item=>item.equip_oid),
    sizeUnit:sizeSend.value,
    userAccount:JSON.parse(localStorage.getItem("userMessage")).user_account,
  }

  try{
    await PushModelCalDatasToDataCenter(data)
   ElMessage({
     message: "已经成功推送至数据中心",
     type: "success",
   });
  }catch(err){
    ElMessage({
     message: "推送失败，请重试",
     type: "error",
   });
  }
 
}

let mulitExportEquipCalData = async () => {
  if (sectionTableData.value.length == 0) {
    ElMessage({
      message: "请选择要输出的设备",
      type: "warning",
    });
    return;
  }
  let str = "";
  sectionTableData.value.forEach(async (v, i) => {
    if (i == sectionTableData.value.length - 1) {
      str += `equip_oids=${v.equip_oid}`;
    } else {
      str += `equip_oids=${v.equip_oid}&`;
    }
  });

  let res = await ExportZipForModel(str, sizeSend.value);

  let filename = res.headers; //下载后文件名
  let filename2 = ""; //下载后文件名
  filename = filename["content-disposition"];
  filename = window.decodeURI(filename);
  filename2 = filename.split(";")[1].split("filename*=UTF-8''")[1];
  filename = filename.split(";")[1].split("filename=")[1];
  const link = document.createElement("a"); // 创建a标签
  const blo = new Blob([res.data], { type: res.data.type }); // 设置下载格式
  link.style.display = "none";
  const url = window.URL.createObjectURL(blo);
  console.log(url);
  link.href = url;
  if (filename == undefined) {
    filename = filename2;
  }
  link.download = filename;

  // link.setAttribute('download', "fileName")3
  document.body.appendChild(link);
  link.click(); // 触发下载
  window.URL.revokeObjectURL(url); // 释放掉blob对象
  document.body.removeChild(link);
  ElMessage({
    message: "成功生成文件",
    type: "success",
  });
};

let mulitExportEquipData = async () => {
  if (sectionTableData.value.length == 0) {
    ElMessage({
      message: "请选择要导出的设备",
      type: "warning",
    });
    return;
  }
  let str = "";
  sectionTableData.value.forEach(async (v, i) => {
    if (i == sectionTableData.value.length - 1) {
      str += `equip_oids=${v.equip_oid}`;
    } else {
      str += `equip_oids=${v.equip_oid}&`;
    }
  });

  await ExportZipForModelInput(str);
  ElMessage({
    message: "导出成功",
    type: "success",
  });
  window.location.replace(
    `http://10.6.100.80:10002/Exporter/ExportZipForModelInput?${str}`
  );
};

let unit_oidOptions = ref([]);
let newDioFn = async () => {
  let res = await GetUnits({ proj_oid: selectedProject.value.proj_oid });
  if (res) {
    unit_oidOptions.value = res.map((v) => {
      return {
        value: v.unit_oid,
        label: v.unit_no,
      };
    });
  } else {
    unit_oidOptions.value = [];
  }

  newDio.value = true;
};

let SelectEquip_no = ref([]);
let equipEquip_no = ref([]);

let SelectEquip_class = ref([]);
let equipEquip_class = ref([]);

watch(
  () => projectStore.projectInfo,
  (newVal, oldVal) => {
    selectedProject.value = newVal;
    console.log("监视");
    // 更新设备列表
    getEquipmentList(newVal.proj_oid);
  }
);

let SelectMajor = ref([]);
let equipOptions = ref([]);
let drawing_stage = ref([]);
let equip_nameInput = ref([]);
let nameOptions = ref([]);
let custom_att1_val_class = ref([])
watch(
  [
    SelectMajor,
    SelectEquip_no,
    SelectEquip_class,
    equip_nameInput,
    drawing_stage,
    select_installation_mode_class,
    select_equip_designer_class,
    select_equip_checker_class,
    select_auditor_class,
    select_approver_class,
    select_equip_check_class,
    select_model_stage_class,
    custom_att1_val_class
  ],
  () => {
    getEquipmentList(
      projectStore.projectInfo.proj_oid,
      SelectMajor.value,
      SelectEquip_no.value,
      SelectEquip_class.value,
      equip_nameInput.value,
      drawing_stage.value,
      select_installation_mode_class.value,
      select_equip_designer_class.value,
      select_equip_checker_class.value,
      select_auditor_class.value,
      select_approver_class.value,
      select_equip_check_class.value,
      select_model_stage_class.value,
      custom_att1_val_class.value,
    );
  }
);

let getOptions = (data, str) => {
  return [...new Set(data.map((v) => v[str]))]
    .filter((v) => {
      if (v) {
        return v;
      }
    })
    .map((v) => {
      return {
        value: v,
        label: v,
      };
    });
};
let approver_class = ref([])
let auditor_class = ref([])
let equip_checker_class = ref([])
let equip_designer_class = ref([])
let tableHeader  = ref('')
let custom_att1_val_option =ref([])
/* 定义函数内容 */
async function getEquipmentList(
  proj_oid,
  SelectMajorStr = [],
  SelectEquip_no = [],
  SelectEquip_class = [],
  equip_nameInput = [],
  drawing_stage = [],
  installation_mode = [],
  equip_designer=[],
  equip_checker =[],
  auditor=[],
  approver =[],
  equip_check=[],
  model_stage=[],
  custom_att1_val=[],
) {
  table_Loading.value = true
  let tableHeaderStr = await GetEquipCustomAttributes({proj_oid})
  tableHeader.value = tableHeaderStr.custom_att1
  

  let data = await getEquipments({
    proj_oid,
    equip_user: JSON.parse(localStorage.getItem("userMessage")).user_name,
    authCode: localStorage.getItem("authCode"),
    custom_att1: tableHeader.value
  });

  
  equip_checker_class.value = getOptions(data, "equip_checker");
  equipOptions.value = getOptions(data, "equip_unit_no");
  equipEquip_no.value = getOptions(data, "equip_no");
  equipEquip_class.value = getOptions(data, "equip_class");
  nameOptions.value = getOptions(data, "equip_name");
  installation_mode_class.value = getOptions(data, "installation_mode");
  equip_designer_class.value = getOptions(data, "equip_designer");
  auditor_class.value = getOptions(data, "auditor");
  approver_class.value = getOptions(data, "approver");
  equip_check.value = getOptions(data, "equip_check");
  custom_att1_val_option.value = getOptions(data, "custom_att1_val");
 
  // 定义筛选条件
  const filters = {
    equip_unit_no: SelectMajorStr, // num 符合 'R1' 或 'R2'
    equip_no: SelectEquip_no, // id 符合 1
    equip_class: SelectEquip_class,
    equip_name: equip_nameInput,
    drawing_stage: drawing_stage,
    installation_mode:installation_mode,
    equip_designer:equip_designer,
    equip_checker:equip_checker,
    auditor:auditor,
    approver:approver,
    equip_check:equip_check,
    model_stage:model_stage,
    custom_att1_val:custom_att1_val,
  };
  let datas = multiFilter(JSON.parse(JSON.stringify(data)), filters)
  equipments.value = datas;
  table_Loading.value = false
  table_Loadings.value = false
}

function multiFilter(array, filters) {
  const filterKeys = Object.keys(filters);
 
  return array.filter((item) => {
    return filterKeys.every((key) => {
      if (!filters[key].length) return true;
      return !!~filters[key].indexOf(item[key]);
    });
  });
}

// 删除设备
let deleteEquipment = () => {
  if (sectionTableData.value == 0) {
    ElMessage({
      message: "请勾选设备",
      type: "error",
    });
    return;
  }
  ElMessageBox.confirm("此操作将永久删除勾选设备, 是否继续?", "警告", {
    type: "warning",
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    buttonSize: "small",
  }).then(async () => {
    sectionTableData.value.forEach(async (v, i) => {
      await DeleteEquip({ equip_oid: v.equip_oid });
      if (i == sectionTableData.value.length - 1) {
        EquipmentStore.UpgradeEquipCount += 1;
        ElMessage({
          message: "删除成功",
          type: "success",
        });
      }
    });
  });
};

let showINit = ref(false);

/* 定义生命周期函数 */

onMounted(() => {
  sessionStorage.setItem("idid", "124efb77-9be0-4d68-8922-2954b86ae313");
  sessionStorage.setItem(
    "124efb77-9be0-4d68-8922-2954b86ae313",
    JSON.stringify({
      approve_workload: null,
      approver: null,
      audit_workload: null,
      auditor: null,
      basic_workload: null,
      check_finish_time: null,
      check_workload: null,
      condition_iss_time: null,
      condition_return_time: null,
      design_finish_time: null,
      design_workload: null,
      different: [],
      difficulty_factor: null,

      equip_assemble_no: "123",
      equip_check: "2",
      equip_checker: "王汤",
      equip_checktime: "2024-03-04 17:57:32",
      equip_class: "BEM参数化设备",
      equip_count: null,
      equip_createtime: "2024-03-01T10:48:09",
      equip_design_stage: "123",
      equip_designer: "王汤",
      equip_dry_weight: null,
      equip_dwg_no: "123",
      equip_lastmodifytime: "2024-03-07T10:59:25",
      equip_name: "decTest001",
      equip_no: "decTest001",
      equip_oid: "124efb77-9be0-4d68-8922-2954b86ae313",
      equip_type: "卧式设备",
      equip_unit_name: "冷氢化A",
      equip_unit_no: "802A",
      equip_version: "R2",
      examine_workload: null,
      examiner: null,
      hasNewProcess: "False",
      installation_mode: null,
      proj_oid: "29c4d2a4-c900-4831-bb0d-59f75af7a670",
      review_finish_time: null,
      special_material_weight: null,
      storage_time: null,
      unit_oid: "d4a2a260-9477-42b2-a53a-568dab9830d2",
      vessel_type: null,
      workload: null,
    })
  );

  sessionStorage.setItem("showINit", true);

  showINit.value = true;

  setTimeout(() => {
    console.log("加载项目设备");
    selectedProject.value = projectStore.projectInfo;

    // 获取当前项目设备列表

    getEquipmentList(projectStore.projectInfo.proj_oid);
  }, 20);
});
</script>

<style scoped lang="scss">
.project-infor-cards {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.equip-list {
  background-color: #fff;
  min-height: calc(100vh - 367px);
}

.equip-title_span {
  font-weight: bold;
  margin-right: auto;
  font-size: 1.5em;
  padding-left: 8px;
  border-left: 6px solid #67c23a;
}
.equip-buttons {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 8px;
  margin-bottom: 8px;

  .el-button-group {
    display: flex;
    align-items: center;

    margin-left: 16px;
  }
}

.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
</style>
